#pragma once

#include <iostream>
#include <cstdlib>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "log.hpp"
const int defaultsockfd = -1;
const std::string defaultip = "0.0.0.0";
const int backlog = 5;
Log log;
enum
{
    SocketError = 2,
    BindError,
    ListenError
};
class TcpServer
{
public:
    TcpServer(const uint16_t port, const std::string ip = defaultip) : listensockfd_(defaultsockfd), port_(port), ip_(ip)
    {
    }
    void InitServer()
    {
        listensockfd_ = socket(AF_INET, SOCK_STREAM, 0);
        if (listensockfd_ < 0)
        {
            log(Fatal, "create listensockfd_,errno:%d,errstring:%s ", errno, strerror(errno));
            exit(SocketError);
        }
        log(Info, "create listensockfd_ success,listensockfd_:%d ", listensockfd_);
        
        int opt =1;
        setsockopt(listensockfd_,SOL_SOCKET,SO_REUSEADDR|SO_REUSEPORT,&opt,sizeof(opt));

        struct sockaddr_in local;
        // bzero(&local,sizeof(local));
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port_);
        // local.sin_addr.s_addr = inet_addr(ip_.c_str()); //INADDR_ANY
        inet_aton(ip_.c_str(), &(local.sin_addr));
        int retval = bind(listensockfd_, (const struct sockaddr *)&local, (socklen_t)sizeof(local));
        if (retval < 0)
        {
            log(Fatal, "bind error,errno:%d,errstring:%s ", errno, strerror(errno));
            exit(BindError);
        }
        log(Info, "bind success...listensockfd_: %d ", listensockfd_);
        if (listen(listensockfd_, backlog) < 0)
        {
            log(Fatal, "listen error,errno:%d ,errstring:%s ", errno, strerror(errno));
            exit(ListenError);
        }
        log(Info, "listen success...listensockfd_:%d ", listensockfd_);
    }
    void Start()
    {
        sleep(1);
        log(Info, "tcpServer is running...");
        while (true)
        {
            // 1.获取新链接
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            int sockfd = accept(listensockfd_, (struct sockaddr*)&client,&len);
            if(sockfd < 0)
            {
                log(Warning, "accept error,errno:%d ,errstring:%s ", errno, strerror(errno));
                continue;
            }
            uint16_t clientport = ntohs(client.sin_port);
            char clientip[32];
            inet_ntop(AF_INET,&(client.sin_addr),clientip,sizeof(clientip));
            
            // 2.根据新链接来进行通信
            log(Info,"get a new link...sockfd:%d,client ip:%s,client port:%d ",sockfd,clientip,clientport);
            Service(sockfd,clientip,clientport);
        }
    }
    void Service(int sockfd,const std::string &clientip,const uint16_t clientport)
    {
        //test code
        char buffer[4096];
        while(true)
        {
            ssize_t n = read(sockfd,buffer,sizeof(buffer));
            if(n <= 0) {
                log(Warning,"read error...");
            }
            buffer[n] = 0;
            std::cout<<"client say# "<<buffer<<std::endl;
            std::string echo_string = "tcpserver echo# ";
            echo_string += buffer;
            write(sockfd,echo_string.c_str(),echo_string.size());
        }
    }
    ~TcpServer() {}

private:
    int listensockfd_;
    uint16_t port_;
    std::string ip_;
};